package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import com.alipay.zxy.alipayplugin.message.response.AlipayTradePayDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 支付宝代扣扣款服务
 *
 * @author zxy
 * @date 2019-06-28
 */
@Slf4j
@Service
public class AlipayTradePayService extends BaseService {

    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayTradePayService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipayTradePayDTO pay(AlipayTradePayModel alipayModel) throws AlipayApiException {
        AlipayTradePayDTO payDTO;
        alipayModel.setProductCode("GENERAL_WITHHOLDING");
        AlipayTradePayRequest alipayRequest = new AlipayTradePayRequest();
        alipayRequest = (AlipayTradePayRequest) getAlipayRequest(alipayRequest, alipayConfig, alipayModel);
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        AlipayTradePayResponse alipayResponse = alipayClient.execute(alipayRequest);
        if (alipayResponse.isSuccess()) {
            log.info("支付宝扣款返回值 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            // TODO 该处可以根据业务需要自行修改返回值
            payDTO = new AlipayTradePayDTO();
            payDTO.setBuyerUserId(alipayResponse.getBuyerUserId());
            payDTO.setGmtPayment(alipayResponse.getGmtPayment().getTime());
            payDTO.setOutTradeNo(alipayResponse.getOutTradeNo());
            payDTO.setTotalAmount(alipayResponse.getTotalAmount());
            payDTO.setTradeNo(alipayResponse.getTradeNo());
            payDTO.setReceiptAmount(alipayResponse.getReceiptAmount());
            return payDTO;
        } else {
            log.info("支付宝扣款错误 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return null;
        }
    }
}
